package com.finsiot.tools.taos.migration;

import com.finsiot.tools.taos.migration.bean.DataBase;
import com.finsiot.tools.taos.migration.bean.DataTypeEnum;
import com.finsiot.tools.taos.migration.bean.TableRelation;
import com.finsiot.tools.taos.util.Constant;
import com.finsiot.tools.taos.util.ParameterUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.cli.*;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;

/**
 * Hello world!
 */
@Slf4j
public class ExportApp {
//    private static final LinkedBlockingQueue<Runnable> linkedBlockingQueue = new LinkedBlockingQueue<Runnable>();
//    private static final ThreadFactory namedThreadFactory = new ThreadFactory() {
//        public Thread newThread(Runnable r) {
//            Thread thread = new Thread(r, String.valueOf(r.hashCode()));
//            thread.setDaemon(true);//设置成守护线程
//            return thread;
//        }
//    };
//
//    private  static ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(4, 8, 5, TimeUnit.MINUTES,
//            linkedBlockingQueue,
//            namedThreadFactory,
//            new RejectedExecutionHandler() {
//                @Override
//                public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
//                    System.err.println("当前的任务已经被拒绝: " + r.toString());
//                }
//            });
    static Pattern regex = Pattern.compile( "^[1-9]\\d*$");

    static HashMap<String, TableRelation>  tableRelationHashMap=new HashMap<>();;
    static String filePath;
    static  Connection connection;

    public static void main(String[] args) throws SQLException, IOException {
        CommandLineParser commandLineParser = new DefaultParser();
        Options options = new Options();
        options.addOption(Constant.HOST, "127.0.0.1",true, "数据库地址");
        options.addOption(Constant.PORT, "6041",true, "数据库端口");
        options.addOption(Constant.DATABASE,  "alinks",true,"数据库名称");
        options.addOption(Constant.USERNAME, "root",true,"用户名");
        options.addOption(Constant.PASSWORD, "taosdata",true, "用户密码");
        options.addOption(Constant.KEEP,  "365",true,"保存数据天数");
        options.addOption(Constant.PRECISION,  "ms",true,"时间精度：ms 毫秒，us 微妙，ns 纳秒");
        options.addOption(Constant.CONTENT, "all",false, "内容：meta 元数据，data 数据，all 元数据和数据一起");
        options.addOption(Constant.DATA_PATH, "./",true, "导出数据的存放目录");

        if(args.length<16){
            System.out.println(ParameterUtils.getHelp(options));
        }

        System.exit(0);

        CommandLine commandLine = null;
        try {
            commandLine = commandLineParser.parse(options, args);
        } catch (ParseException e) {
            e.printStackTrace();
            System.out.println(ParameterUtils.getHelp(options));
        }
        String host = commandLine.getOptionValue(Constant.HOST);
        Integer port = Integer.parseInt(commandLine.getOptionValue(Constant.PORT));
        String database = commandLine.getOptionValue(Constant.DATABASE);
        String username = commandLine.getOptionValue(Constant.USERNAME);
        String password = commandLine.getOptionValue(Constant.PASSWORD);
        Integer keep = Integer.parseInt(commandLine.getOptionValue(Constant.KEEP));
        String precision = commandLine.getOptionValue(Constant.PRECISION);
        DataTypeEnum dataTypeEnum = DataTypeEnum.valueOf(commandLine.getOptionValue(Constant.CONTENT));
        filePath = commandLine.getOptionValue(Constant.DATA_PATH);

        DataBase dataBase = new DataBase(host, port, database, username, password, precision, keep);

        Long start = System.currentTimeMillis();
        connection = dataBase.createConnection();

        ExportMeta exportMeta = new ExportMeta(connection, filePath);


        List<String> stableList = exportMeta.getSuperTables();
        //获取超级表与子表关系
        for (String stable : stableList) {
            tableRelationHashMap.put(stable, exportMeta.getSonTableInfo(stable));
        }

        log.info("扫描结果：有超级表:{},有普通单表:{}", stableList.size(), exportMeta.getTableList().size());

        ExportData exportData = new ExportData(connection, filePath);

        switch (dataTypeEnum){
            case all:
                exportMeta.exportMeta(tableRelationHashMap);
                System.out.println("元数据导出数据完成。 ");
                exportData.exportData(tableRelationHashMap, dataBase.getKeep(), dataBase.getPrecision());
                break;

            case meta:
                exportMeta.exportMeta(tableRelationHashMap);
                System.out.println("元数据导出数据完成。 ");
                break;
            case data:
                exportData = new ExportData(connection, filePath);
                exportData.exportData(tableRelationHashMap, dataBase.getKeep(), dataBase.getPrecision());
                break;
            default:
        }

        connection.close();
        Long end = System.currentTimeMillis();

        long westTime = (end - start) / 1000;

        log.info("导出数据耗时：{}分钟{}秒", (westTime / 60), (westTime % 60));

    }
}
